var objectURL = 'http://localhost:5000/js/api_overview_.json';

var getListeners = [];

var isYouTubeID = function(s) {
  return /^[A-Za-z0-9_-]{11}$/.test(s);
};

var Objects = {
  objects: null,
  get: function(callback) {
    if (this.objects) {
      callback(this.objects, this.objectIndex);
    } else {
      getListeners.push(callback);
      if (getListeners.length === 1) {
        var self = this;
        // $http({ method: 'GET', cache: true, url: objectURL }).success(function(objectArr) {
        fetch(objectURL).then(res => res.json()).then(function(objectArr) {
          // console.log('Object', objectArr);
          if (typeof objectArr === 'string') {
            objectArr = JSON.parse(objectArr.slice(5));
          }
          self.objects = [];
          self.objectsByCategory = {};
          self.objectIndex = {};
          objectArr.forEach(function(obj) {
            obj.categoryName = (obj.categoryName + '').toLowerCase();
            if (obj.categoryName === 'jewellery') {
              obj.categoryName = 'trade and conflict';
            } else if (obj.categoryName === 'weapon') {
              obj.categoryName = 'art and design';
            } else if (obj.categoryName === 'tool') {
              obj.categoryName = 'living and dying';
            } else if (obj.categoryName === 'art') {
              obj.categoryName = 'power and identity'
            }
            var cat = self.objectsByCategory[obj.categoryName];
            if (!cat) {
              cat = self.objectsByCategory[obj.categoryName] = [];
            }
            cat.push(obj);
            if (obj.categoryName === 'null') {
              obj.categoryObjects = [];
            } else {
              obj.categoryObjects = cat;
            }
            obj.bullet = obj.bullet.replace(/[^a-z0-9]/gi, '-');
            if (!self.objectIndex[obj.bullet]) {
              self.objectIndex[obj.bullet] = obj;
              self.objects.push(obj);
              obj.mapParams = {
                center: {lat: obj.lat, lng: obj.lng},
                zoom: obj.zoomLevel
              };
            } else {
              //console.log('duplicate object!', obj.bullet);
            }

            obj.audioClips.forEach(function(audio) {
              // audio.mainURL = $sce.trustAsResourceUrl(audio.mainURL);
              // console.log(audio.mainURL);
              audio.mainURL = audio.mainURL;
            });

            obj.youTubeIds = [];
            if (obj.youtubeVideo && isYouTubeID(obj.youtubeVideo)) {
              obj.youTubeIds.push({ mainURL: obj.youtubeVideo });
            }

          });
          for (var i in self.objectsByCategory) {
            self.objectsByCategory[i].sort(function(a,b) { return a.dateCreated - b.dateCreated; });
          }
          getListeners.forEach(function(f) { f(self.objects, self.objectIndex); });
          getListeners = [];
        });
      }
    }
  }
};
